<?php

namespace Model;

use Daiyong\Db as db;

class UserGroup extends Common {
    public $table = 'user_group';

    public function rule() {
        return array(
            'name|must' => array(
                array('string', '用户组名称必须在2~10个字符之间', 2, 10),
                array('only', '用户组名称与已有数据重复,请修改', $this->table),
            )
        );
    }
    public function find($param) {
        $data = toArray(db::find($this->table, $param));
        return $data;
    }
    public function findAll($param = [], $orderBy = 'order by id desc', $limit = 'limit 0,1000') {
        $param = $this->findClear($param);
        $list = db::findAll($this->table, $param, $orderBy . ' ' . $limit);
        return $list;
    }
    public function export($param = [], $orderBy = '') {
        $title =  ['id', '用户组名称'];
        $filePath = $this->exportExcel($title, function ($limit) use ($param, $orderBy) {
            $list = $this->findAll($param, $orderBy, $limit);
            foreach ($list as $k => $v) {
                //行内容设置与$title一一对应
                $list[$k] = array($v['id'], $v['name']);
            }
            return $list;
        });
        return $filePath;
    }
    public function edit($data) {
        $verify = $this->verify($data, $this->rule());
        if ($verify !== true) {
            return $this->error($verify);
        }
        $data = $this->auto($data); //加入或去除一些自动生成的字段
        if ($data['id']) {
            return db::update($this->table, $data, ['id' => $data['id']]);
        } else {
            return db::insert($this->table, $data);
        }
    }
    public function delete($param) {
        if (!$param['id']) return $this->error('为避免错误请传入id删除');
        //相关联信息判断
        $data = db::find($this->table, $param);
        if ($data['id']) {
            $check = db::find('user', ['gid' => $data['id']]);
            if ($check) {
                return $this->error('该用户组下还存在用户,暂时不允许删除,如需删除请先修改或删除组下用户');
            }
        }
        //开始删除
        return db::delete($this->table, $param);
    }
    private function auto($data) {
        return $data;
    }
}
